package com.ease.util {

   import mx.core.FlexGlobals;

   /**
    * Utility functions for working with <code>Function</code> objects.
    */
   public class FunctionUtil {

      /**
       * Contains the set of fucntions which have been requested for execution,
       * but still have not been invoked.
       */
      private static var _scheduledCalls:Set = new Set();

      /**
       * Same as the <code>UIComponent.callLater</code> method, but avoids multiple
       * ivocations of the same function, if <code>callLater</code> is used more than
       * once in the same frame with the same function as parameter.
       *
       * @param f
       *    The function to invoke later.
       *
       * @param args
       *    An array containing the arguments to pass to the function <code>f</code>.
       *
       * @param avoidMultipleInvocations
       *    This ensures that for example if you use <code>callLater</code> twice in
       *    the same frame with the same function, the requested function will execute
       *    only once.
       *
       */
      public static function callLater(f:Function,
                                       args:Array /* of Object */ = null,
                                       avoidMultipleInvocations:Boolean = true):void {
         if (avoidMultipleInvocations && _scheduledCalls.contains(f)) {
            return;
         }

         _scheduledCalls.add(f);

         FlexGlobals.topLevelApplication.callLater(invokeCallLater, [f, args]);
      }

      /**
       * An internal helper method.
       */
      private static function invokeCallLater(f:Function, args:Array):void {
         _scheduledCalls.remove(f);
         f.apply(null, args);
      }

   } // class
} // package
